package com.css.chat.logic.chat.message.res;

import com.css.chat.netty.message.AbstractPacket;
import com.css.chat.netty.message.PacketType;
import com.css.chat.util.CommonUtil;
import io.netty.buffer.ByteBuf;
import org.bytedeco.javacv.CanvasFrame;

import java.awt.*;

/**
 * @description: 发送图片
 * @author: zyj
 * @create: 2020-02-21 14:30
 **/
public class ResVideoImgToUser extends AbstractPacket {


    private long fromUserId;
    /**0:关闭 1：打开*/
    private int close;
    private byte[] videoImg;

    public long getFromUserId() {
        return fromUserId;
    }

    public void setFromUserId(long fromUserId) {
        this.fromUserId = fromUserId;
    }

    public int getClose() {
        return close;
    }

    public void setClose(int close) {
        this.close = close;
    }

    public byte[] getVideoImg() {
        return videoImg;
    }

    public void setVideoImg(byte[] videoImg) {
        this.videoImg = videoImg;
    }

    @Override
    public void writeBody(ByteBuf buf) {
        buf.writeLong(fromUserId);
        buf.writeInt(close);
        buf.writeInt(videoImg.length);
        buf.writeBytes(videoImg);
    }

    @Override
    public void readBody(ByteBuf buf) {
        this.fromUserId = buf.readLong();
        this.close = buf.readInt();
        int length = buf.readInt();
        videoImg = new byte[length];
        buf.readBytes(videoImg);
    }

    @Override
    public PacketType getPacketType() {
        return PacketType.RES_VIDEO_DNL_IMG;
    }

    @Override
    public void execPacket() {
        CanvasFrame canvas = CommonUtil.showCanvas(String.valueOf(fromUserId));
        if(close==1){
            Image imageh = Toolkit.getDefaultToolkit().createImage(videoImg);
            try {
                MediaTracker mt = new MediaTracker(new Label());
                mt.addImage(imageh, 0);
                mt.waitForAll();
                canvas.showImage(imageh);//获取摄像头图像并放到窗口上显示，frame是一帧视频图像
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(close==0){
            canvas.setVisible(false);
            CommonUtil.countCav.remove(String.valueOf(fromUserId));
        }
    }


}
